<template>
  <div id="hls">
    <video :id="'video'+hlsKey" muted controls style="width: 100%;
     height: 100%;
     object-fit: cover;"></video>
  </div>
</template>
<script>
  import hlsjs from "hls.js";

  export default {
    name: 'hls-video',
    props: {
      src: String,
      hlsKey: Number,
      width: Number,
      height: Number
    },
    components: {},
    data() {
      return {}
    },

    methods: {
      //初始化video
      initVideo() {
        let video = document.getElementById('video' + this.hlsKey)
        if (hlsjs.isSupported()) {
          this.hlsjs = new hlsjs()
          //该hls地址为nginx配置中的地址
          // http://192.168.1.108:7086/live/cameraid/1000002%240/substream/1.m3u8
          this.hlsjs.loadSource(this.src)
          this.hlsjs.attachMedia(video)
          this.hlsjs.on(hlsjs.Events.MANIFEST_PARSED, () => {
            video.play()
          });
          // hls.on(hlsjs.Events.ERROR, (event, data) => {
          //   console.log(event, data);
          //   // 监听出错事件
          //   console.log('加载失败');
          // });
        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
          video.src = this.src
          video.addEventListener('loadedmetadata', function () {
            video.play()
          })
        }
      }
    },
    created() {
    },
    mounted() {
      this.initVideo()
    },
    computed: {},
    watch: {
      src: {
        handler(val, oldVal){
          this.initVideo()
        },
        deep:true //true 深度监听
      }
    }
  }
</script>
<style scoped>
</style>
